package com.codingfuture.service.impl;

import com.codingfuture.entity.Exam;
import com.codingfuture.entity.Question;
import com.codingfuture.mapper.QuestionMapper;
import com.codingfuture.service.ExamService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Service
public class ExamServiceImpl implements ExamService {

    @Autowired
    public QuestionMapper questionMapper;

    @Override
    public OutputStream genExamWordStream(Exam[] exams) {
        URI templateUri = null;
        try {
            templateUri = this.getClass().getClassLoader().getResource("template.docx").toURI();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        XWPFTemplate template = XWPFTemplate.compile(new File(templateUri));

        NiceXWPFDocument document = template.getXWPFDocument();

        XWPFParagraph p1 = document.createParagraph();
        XWPFRun run1 = p1.createRun();
        run1.setFontSize(20);
        run1.setBold(true);
        run1.setText("一、简答题（共100分）");

        int i = 0;
        Map<String, Object> map = new HashMap<>();
        for (Exam exam : exams) {
            i++;
            Question question = questionMapper.findById(exam.getQid());
            exam = new Exam(question, exam.getScore());

            XWPFParagraph p2 = document.createParagraph();
            XWPFRun run2 = p2.createRun();
            run2.setFontSize(16);
            run2.setText(String.format("%d. %s（%d分）", i, exam.getTitle(), exam.getScore()));
            if (exam.getImgPath() != null) {
                XWPFParagraph p3 = document.createParagraph();
                InputStream inputStream = getImageStream(exam.getImgPath());
                try {
                    BufferedImage image = ImageIO.read(inputStream);
                    int width = image.getWidth();
                    int height = image.getHeight();

                    p3.createRun().addPicture(bufferedImageToInputStream(image), XWPFDocument.PICTURE_TYPE_JPEG,
                            "1.jpg", Units.toEMU(width/5), Units.toEMU(height/5));

//                    inputStream.close();
                } catch (InvalidFormatException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            for (int j = 0; j < 5; j++) {
                document.createParagraph();
            }
        }

        OutputStream out = null;
        try {
            out = new ByteArrayOutputStream();
            template.write(out);
            template.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return out;

    }

    private InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }

    private InputStream bufferedImageToInputStream(BufferedImage image){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
            return new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
